package com.ipar_shop.utils;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.util.ArrayList;
import java.util.List;

/**
 * 原生模块
 */
public class MyCommonJava extends ReactContextBaseJavaModule {

    private static final String DURATION_SHORT_KEY = "SHORT";
    private static final String DURATION_LONG_KEY = "LONG";

    public MyCommonJava(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    /**
     * @return js调用的模块名
     */
    @Override
    public String getName() {
        return "MyCommonJava";
    }

    /**
     * 使用ReactMethod注解，使这个方法被js调用
     *
     * @param filePaths url
     */
    @ReactMethod
    public void downloadImage(String filePaths, Callback success, Callback error) {
        try {
            List<String> permissionList = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(getReactApplicationContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (!permissionList.isEmpty()) {
                String[] permissions = permissionList.toArray(new String[permissionList.size()]);
                ActivityCompat.requestPermissions(getCurrentActivity(), permissions, 1);
                error.invoke();
            } else {
                DownloadSaveImg.downloadImg(getCurrentActivity(), filePaths, success, error);//iPath
            }
        } catch (Exception e) {
            error.invoke("error");
        }
    }


}